<template>

  <div class="table1_container">
    <div class="table1_dataShower" style="padding-bottom: 50px; padding-top: 50px; box-sizing: border-box">
      <button class="report-top-button" @click="back">返回上级页面</button>

      <button class="report-top-button" @click="openFieldDialog">选择字段</button>
      <button class="report-top-button" @click="printReport">报表打印</button>
      <div style="text-align: center; margin: 10px 0;">
        <div style="display: inline-flex; gap: 20px;">
          <!-- 未完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffffff; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>未完成</span>
          </div>

          <!-- 已完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #e6f7e6; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>已完成</span>
          </div>

          <!-- 不合格重采 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffebeb; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>不合格重采</span>
          </div>
        </div>
      </div>
      <h1>见证取样记录</h1>
      <!-- 基本信息部分 - 在表格上方 -->
      <div class="project-name-info" style="width:90%;margin:0 auto;display: flex">
        <div style="text-align: left">
          <span>工程名称:</span>
          <span>{{ projectName + '  ' + subprojectName }}</span>
        </div>
      </div>
      <table class="wendu-table1_top_table">
        <tr>
          <template v-for="field in tableHeaders">
            <td :key="field.key" :colspan="field.colspan || 1"><strong>{{ field.label }}</strong></td>
          </template>
        </tr>
        <tr v-for="(item, index) in reportData" :key="index">
          <template v-for="field in tableHeaders">
            <td :key="field.key + '-' + index" :colspan="field.colspan || 1">{{ getFieldValue(item, field.key) }}</td>
          </template>
        </tr>
        <tr class="hanjie-jianzheng-table-bottom">
          <td :colspan="Math.ceil(totalColumns / 2)">施工单位（签章）</td>
          <td :colspan="Math.floor(totalColumns / 2)">见证单位（签章）</td>
        </tr>

        <tr class="hanjie-jianzheng-table-bottom">
          <td :colspan="Math.ceil(totalColumns / 2)">取样人：</td>
          <td :colspan="Math.floor(totalColumns / 2)">见证人：</td>
        </tr>

        <tr class="hanjie-jianzheng-table-bottom">
          <td style="text-align: right" :colspan="Math.ceil(totalColumns / 2)">
            <span style="letter-spacing: 2em">年月日</span>
          </td>
          <td style="text-align: right" :colspan="Math.floor(totalColumns / 2)">
            <span style="letter-spacing: 2em">年月日</span>
          </td>
        </tr>
      </table>
    </div>

    <!-- 字段选择对话框 -->
    <el-dialog
      title="选择显示字段"
      :visible.sync="fieldDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <div style="max-height: 500px; overflow-y: auto;">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          style="margin-bottom: 15px;"
        >
          全选
        </el-checkbox>
        <el-divider></el-divider>
        <el-checkbox-group v-model="selectedFields" @change="handleCheckedFieldsChange">
          <div
            v-for="field in allFields"
            :key="field.key"
            style="margin-bottom: 10px;"
          >
            <el-checkbox :label="field.key">{{ field.label }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fieldDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmFieldSelection">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

/*
 *    这个报表真麻烦！！！
 *
 */

import { searchJianZhengPreview } from '@/api/statementManage/hunNingTu/hunNingTu'

export default {
  data() {
    return {
      localStorageId: '',
      reportData: {},
      previewData: {},
      projectName: '',
      subprojectName: '',
      // 字段选择相关
      fieldDialogVisible: false,
      checkAll: true,
      isIndeterminate: false,
      selectedFields: [], // 选中的字段key数组
      allFields: [ // 所有可用字段
        { key: 'sampleName', label: '样品名称及规格', colspan: 4 },
        { key: 'usePart', label: '取样部位', colspan: 4 },
        { key: 'representAmount', label: '批量', colspan: 2 },
        { key: 'number', label: '数量', colspan: 2 },
        { key: 'checkDate', label: '日期（取样）', colspan: 3 },
        { key: 'delegateNumber', label: '委托编号', colspan: 3 }
      ]
    }
  },
  computed: {
    // 生成表头结构
    tableHeaders() {
      return this.allFields.filter(field => this.selectedFields.includes(field.key))
    },
    // 计算总列数
    totalColumns() {
      return this.tableHeaders.reduce((sum, field) => sum + (field.colspan || 1), 0)
    }
  },
  async mounted() { // 钩子函数
    const sessionData = sessionStorage.getItem('tempObj1')

    const parseData = JSON.parse(sessionData)
    this.projectName = parseData.projectName
    this.subprojectName = parseData.subprojectName
    const subprojectId = parseData.subprojectId
    const projectId = parseData.projectId

    const { result } = await searchJianZhengPreview(projectId, subprojectId, '同条件养护')

    this.reportData = result
    console.log(JSON.stringify(result))

    // 初始化字段选择（默认全选）
    this.selectedFields = this.allFields.map(f => f.key)
    this.checkAll = true
    this.isIndeterminate = false
  },
  beforeDestroy() { // 离开页面要做的事
    document.querySelector('body').setAttribute('style', 'background-color: white;') // 还原，因为这是个全局样式
  },
  beforeCreate() {
    document.querySelector('body').setAttribute('style', 'background-color:#f5f5f5;') // 设置对比色
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    // 打开字段选择对话框
    openFieldDialog() {
      this.fieldDialogVisible = true
    },
    // 全选/取消全选
    handleCheckAllChange(val) {
      this.selectedFields = val ? this.allFields.map(f => f.key) : []
      this.isIndeterminate = false
    },
    // 字段选择变化时更新全选状态
    handleCheckedFieldsChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.allFields.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allFields.length
    },
    // 确认字段选择
    confirmFieldSelection() {
      if (this.selectedFields.length === 0) {
        this.$message.warning('请至少选择一个字段！')
        return
      }
      this.fieldDialogVisible = false
      this.$message.success('字段选择已更新！')
    },
    // 打印报表
    printReport() {
      window.print()
    },
    // 根据字段key获取对应的值
    getFieldValue(item, fieldKey) {
      const valueMap = {
        'sampleName': (item.maintCondition ? item.maintCondition + ' ' : '') + (item.concreteStrength || ''),
        'usePart': item.usePart,
        'representAmount': item.representAmount,
        'number': item.number,
        'checkDate': item.checkDate,
        'delegateNumber': item.delegateNumber
      }
      return valueMap[fieldKey] || ''
    }
  }
}
</script>

<style>
@import '../../../../assets/css/concrete/jianzheng.css';

/*
先来设置每个任务项对应的背景颜色吧！
 */
.row-unfinished {
  background-color: #ffffff; /* 未完成 - 白色或默认色 */
}

.row-finished {
  background-color: #e6f7e6; /* 已完成 - 浅绿色 */
}

.row-failed {
  background-color: #ffebeb; /* 不合格重采 - 浅红色 */
}

.table1_container {
  width: 80%;
  background: white;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding-bottom: 20px;
}

.table1_dataShower {
  width: 80%;
  background: white;
  margin: 0 auto;
  border: 2px black solid;
}

/*这是返回按钮的样式*/
.report-top-button {
  display: block;
  margin: 0 auto;
  margin-bottom: 20px;
  padding: 12px 28px;
  font-size: 16px;
  font-weight: 600;
  font-family: 'Arial', sans-serif;
  color: #ffffff;
  background: linear-gradient(90deg, #1e3a8a, #3b82f6); /* 建筑行业蓝色调，稳重且有活力 */
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.report-top-button:hover {
  background: linear-gradient(90deg, #1e3a8a, #2563eb);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.report-top-button:active {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  transform: translateY(0);
}

/*表格样式*/
.wendu-table1_top_table {
  width: 90%;
  margin: 0 auto;
  border-collapse: collapse;
  border: 1px solid black;
  table-layout: fixed;
}

/*表格的样式*/
.wendu-table1_top_table tr td {
  height: 50px;
  border: 1px solid black;
  word-wrap: break-word; /* 允许长单词换行 */
  overflow-wrap: break-word; /* 更现代的换行属性 */
}

#table1_top_table_last_col {
  width: 20%;
  min-height: 50px;
}

th {
  box-sizing: border-box !important;
}

.hanjie-jianzheng-table-bottom td {
  text-align: left;
  border: none !important;
  border-right: 1px solid black !important;
  padding: 10px !important;
}

@media print {

  .table1_container {
    width: 100% !important;
    margin: 0 0 !important;
    font-size: 14px !important;
  }

  .table1_dataShower {
    width: 100% !important;
    margin: 0 0 !important;
    padding: 15px !important;
    border: none !important;
    font-size: 13px !important;
  }

  /* 确保工程名称在打印时可见 */
  .project-name-info {
    display: flex !important;
    width: 90% !important;
    margin: 10px auto !important;
    font-size: 14px !important;
  }

  .project-name-info div {
    display: block !important;
  }

  .report-top-button {
    display: none !important;
  }

  /* 隐藏图例，但保留工程名称 */
  .table1_dataShower > div:not(.project-name-info) {
    display: none !important;
  }

  .wendu-table1_top_table tr td {
    height: 45px !important;
    font-size: 12px !important;
  }

  h1 {
    font-size: 20px !important;
  }

  @page {
    size: A4 portrait;
    margin-top: 20px;
    margin-bottom: 20px;
  }

}
</style>

